<template>
  <view class="container">
    <view class="header">
      <view class="avatar-section">
        <image class="avatar" :src="userInfo.avatarUrl || '/static/images/avatar.gif'" mode="aspectFill" @tap="chooseAvatar"></image>
        <text class="tip">点击更换头像</text>
      </view>
    </view>

    <view class="form-group">
      <!-- <view class="form-item">
        <text class="label">用户名</text>
        <input type="text" v-model="userInfo.username" placeholder="请输入用户名" :disabled="true"/>
      </view> -->
      
      <view class="form-item">
        <text class="label">昵称</text>
        <input type="text" v-model="userInfo.nickname" placeholder="请输入昵称"/>
      </view>

      <view class="form-item">
        <text class="label">性别</text>
        <picker :range="genderOptions" @change="onGenderChange" :value="genderIndex">
          <view class="picker">{{userInfo.gender || '请选择'}}</view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">手机号</text>
        <input type="number" v-model="userInfo.phone" placeholder="请输入手机号"/>
      </view>

      <view class="form-item">
        <text class="label">邮箱</text>
        <input type="text" v-model="userInfo.email" placeholder="请输入邮箱"/>
      </view>

      <view class="form-item">
        <text class="label">个性签名</text>
        <textarea v-model="userInfo.signature" placeholder="请输入个性签名" maxlength="100"/>
      </view>
    </view>

    <view class="btn-group">
      <button class="save-btn" @tap="saveUserInfo">保存修改</button>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request'
import { BASE_URL, SERVICE_PREFIX } from '@/utils/request'

export default {
  data() {
    return {
      userInfo: {
        userId: '',
        username: '',
        nickname: '',
        avatarUrl: '',
        signature: '',
        phone: '',
        email: '',
        gender: null
      },
      genderOptions: ['男', '女'],
      genderIndex: -1
    }
  },
  onLoad() {
    // 页面加载时获取用户信息
    this.loadUserInfo()
  },
  methods: {
    async loadUserInfo() {
      try {
        // 从本地存储获取用户ID
        const userInfoStorage = uni.getStorageSync('userInfo')
        if (!userInfoStorage || !userInfoStorage.userId) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
          return
        }

        console.log('当前用户ID:', userInfoStorage.userId)
        
        // 显示加载中提示
        uni.showLoading({
          title: '加载中...'
        })

        // 调用后端API获取最新用户信息
        const res = await request.login.get('/api/user/getUserInfo', {
          userId: userInfoStorage.userId
        })
        
        uni.hideLoading()
        console.log('获取用户信息响应:', res)
        
        if (res.code === 200) {
          this.userInfo = res.data
          
          // 设置性别选择器的索引
          this.genderIndex = this.genderOptions.indexOf(this.userInfo.gender)
        } else {
          uni.showToast({
            title: res.msg || '获取用户信息失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        uni.hideLoading()
        console.error('加载用户信息失败:', error)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    },

    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 显示上传中提示
          uni.showLoading({
            title: '上传中...'
          })
          
          // 先尝试标准的文件上传方式
          this.uploadAvatar(tempFilePath)
            .catch(error => {
              console.log('标准上传失败，尝试备用上传方式', error)
              // 如果标准上传失败，尝试Base64上传
              return this.uploadAvatarAsBase64(tempFilePath)
            })
            .then(avatarUrl => {
              // 设置新的头像URL
              this.userInfo.avatarUrl = avatarUrl
              
              uni.hideLoading()
              uni.showToast({
                title: '头像更新成功',
                icon: 'success'
              })
            })
            .catch(error => {
              uni.hideLoading()
              console.error('所有上传方式均失败:', error)
              uni.showToast({
                title: '头像上传失败: ' + (error.message || '未知错误'),
                icon: 'none'
              })
            })
        }
      })
    },
    
    // 标准的文件上传方法
    uploadAvatar(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: BASE_URL + SERVICE_PREFIX.LOGIN + '/api/user/updateAvatarUrl',
          filePath: filePath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            'Accept': '*/*'
          },
          formData: {
            userId: this.userInfo.userId
          },
          success: (uploadRes) => {
            console.log('上传响应原始数据:', uploadRes)
            
            try {
              const result = JSON.parse(uploadRes.data)
              console.log('头像上传结果:', result)
              
              if (result.code === 200) {
                resolve(result.data)
              } else {
                reject(new Error(result.msg || '上传失败'))
              }
            } catch (e) {
              console.error('解析上传结果失败:', e, uploadRes.data)
              reject(new Error('返回格式错误'))
            }
          },
          fail: (err) => {
            console.error('头像上传失败:', err)
            reject(err)
          }
        })
      })
    },

    onGenderChange(e) {
      this.genderIndex = e.detail.value
      this.userInfo.gender = this.genderOptions[this.genderIndex]
    },

    async saveUserInfo() {
      try {
        // 表单验证
        if (this.userInfo.phone && !/^1[3-9]\d{9}$/.test(this.userInfo.phone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          })
          return
        }

        if (this.userInfo.email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.userInfo.email)) {
          uni.showToast({
            title: '请输入正确的邮箱',
            icon: 'none'
          })
          return
        }

        console.log('准备提交的用户信息:', this.userInfo)
        
        // 显示加载中提示
        uni.showLoading({
          title: '保存中...'
        })

        // 准备提交的数据
        const updateData = {
          userId: this.userInfo.userId,
          username: this.userInfo.username,
          nickname: this.userInfo.nickname,
          phone: this.userInfo.phone,
          email: this.userInfo.email,
          signature: this.userInfo.signature,
          gender: this.userInfo.gender,
          avatarUrl: this.userInfo.avatarUrl
        }

        // 添加调试信息
        console.log('提交的数据:', JSON.stringify(updateData))

        const res = await request.login.post('/api/user/updateUserInfo', updateData)

        uni.hideLoading()
        console.log('保存用户信息响应:', res)
        
        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 更新本地存储的用户信息
          const storageUserInfo = uni.getStorageSync('userInfo')
          if (storageUserInfo) {
            const updatedUserInfo = {
              ...storageUserInfo,
              ...updateData
            }
            uni.setStorageSync('userInfo', updatedUserInfo)
          }
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.msg || '保存失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        uni.hideLoading()
        console.error('保存用户信息失败:', error)
        uni.showToast({
          title: '保存失败: ' + (error.message || JSON.stringify(error)),
          icon: 'none'
        })
      }
    },
    
    // Base64头像上传方法
    async uploadAvatarAsBase64(filePath) {
      return new Promise((resolve, reject) => {
        // 读取图片为base64
        uni.getFileSystemManager().readFile({
          filePath: filePath,
          encoding: 'base64',
          success: async (res) => {
            try {
              const base64Data = res.data
              
              // 调用后端API上传base64图片
              const uploadRes = await request.login.post('/api/user/uploadBase64Avatar', {
                userId: this.userInfo.userId,
                imageData: base64Data,
                fileName: `avatar_${Date.now()}.jpg`
              })
              
              if (uploadRes.code === 200) {
                resolve(uploadRes.data)
              } else {
                reject(new Error(uploadRes.msg || '上传失败'))
              }
            } catch (err) {
              reject(err)
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f6f6f6;
  padding: 20rpx;
}

.header {
  background: #fff;
  padding: 40rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      margin-bottom: 20rpx;
    }
    
    .tip {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.form-group {
  background: #fff;
  border-radius: 12rpx;
  padding: 0 30rpx;
  
  .form-item {
    display: flex;
    align-items: center;
    min-height: 100rpx;
    border-bottom: 1rpx solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      width: 160rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    input, .picker {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    textarea {
      flex: 1;
      height: 160rpx;
      font-size: 28rpx;
      padding: 20rpx 0;
    }
  }
}

.btn-group {
  margin-top: 60rpx;
  padding: 0 30rpx;
  
  .save-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #4080ff;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
    text-align: center;
    
    &:active {
      background: #3070e0;
    }
  }
}
</style> 